<!-- eslint-disable vue/no-mutating-props -->
<template>
    <el-drawer
        :model-value.sync="isPointDrawerShow"
        :show-close="true"
        size="880px"
        :close-on-click-modal="false"
        modal-class="batch-drawer"
        :before-close="beforeClose"
        @closed="handleClose"
        @opened="openCallBack(uploadFromRef)"
    >
        <template #title>
            <h4>批量导入点位</h4>
        </template>
        <template #default>
            <div v-loading="uploadLoading" class="batch-import">
                <el-row>
                    <el-col :span="24">
                        <el-tabs v-model="activeName" size="small" @tab-change="handleChange">
                            <el-tab-pane label="上传点位文件" name="uploadFile">
                                <div class="upload-file">
                                    <el-form ref="uploadFromRef" :model="importForm" label-width="16px">
                                        <el-steps direction="vertical" :active="activeStep">
                                            <el-step title="先选择媒体类型">
                                                <template #description>
                                                    <el-form-item prop="mediaType">
                                                        <el-select
                                                            v-model="importForm.mediaType"
                                                            placeholder="请选择"
                                                            @change="changeMediaType"
                                                        >
                                                            <el-option
                                                                v-for="item in commonList.pointTypeList"
                                                                :key="item.code"
                                                                :label="item.name"
                                                                :value="item.code"
                                                            />
                                                        </el-select>
                                                    </el-form-item>
                                                </template>
                                            </el-step>
                                            <el-step title="下载媒体导入模版">
                                                <template #description>
                                                    <el-form-item>
                                                        <el-button
                                                            type="primary"
                                                            plain
                                                            :disabled="activeStep < 1"
                                                            @click="downLoadTemp"
                                                        >
                                                            下载模板
                                                        </el-button>
                                                    </el-form-item>
                                                </template>
                                            </el-step>
                                            <el-step title="按照模板填写文件，然后上传校验">
                                                <template #description>
                                                    <el-form-item>
                                                        <el-upload
                                                            ref="upload"
                                                            v-model:file-list="uploadFileList"
                                                            class="upload-demo"
                                                            drag
                                                            :limit="1"
                                                            :http-request="httpRequest"
                                                            :disabled="activeStep < 1"
                                                            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv"
                                                            action=""
                                                            :on-remove="onRemove"
                                                        >
                                                            <el-icon class="el-icon--upload">
                                                                <upload-filled />
                                                            </el-icon>
                                                            <div
                                                                class="el-upload__text"
                                                                :class="{ 'is-disable-test': activeStep < 1 }"
                                                            >
                                                                把文件拖拽至此，或点击上传
                                                                <template class="el-upload-span">
                                                                    仅可上传1个文件，支持csv、xls等excel文件
                                                                </template>
                                                            </div>
                                                        </el-upload>
                                                    </el-form-item>
                                                </template>
                                            </el-step>
                                        </el-steps>
                                    </el-form>
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="查询校验结果" name="judgeResult" class="judge-result">
                                <xc-table
                                    v-loading="uploadLoading"
                                    :data="tableData"
                                    :columns="columns"
                                    style="width: 100%"
                                    :row-config="rowConfig"
                                    class="upload-result"
                                    :height="maxTableHeight"
                                >
                                    <template #createTime="{ row }">
                                        <span>{{ row.createTime.substr(0, row.createTime.lastIndexOf(':')) }}</span>
                                    </template>
                                    <template #mediaType="{ row }" width="100px">
                                        <span>{{ mediaTypeFilter(row.mediaType) }}</span>
                                    </template>
                                    <template #checkStatus="{ row }">
                                        <span v-if="+row.checkStatus === 1" type="text" class="status-button">
                                            待校验
                                        </span>
                                        <span v-if="+row.checkStatus === 2" type="text" class="status-button">
                                            校验中
                                        </span>
                                        <div v-if="[3, 5].includes(+row.checkStatus)" type="text" class="status-button">
                                            <div class="success-button">
                                                通过<span>{{ +row.successNum || 0 }}</span>
                                            </div>
                                            <div class="fail-button">
                                                失败<span>{{ +row.failNum || 0 }}</span>
                                            </div>
                                        </div>
                                        <span
                                            v-if="+row.checkStatus === 4"
                                            type="text"
                                            class="status-button fail-button"
                                        >
                                            上传失败
                                        </span>
                                    </template>
                                </xc-table>
                                <p class="result-tip">仅保留近30天的导入记录</p>
                            </el-tab-pane>
                        </el-tabs>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="onCancel(uploadFromRef)"> 取消 </el-button>
                <el-button
                    v-if="activeName === 'uploadFile'"
                    type="primary"
                    :disabled="!fileList.length"
                    @click="onCheckFile"
                >
                    校验
                </el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, defineProps, defineEmits, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { importMedia, downloadTemplate, reloadRecords, sureImport } from '@/api/pointManage';
import { Upload } from '@x-tech/fe-puma-lib-upload';
import { getSuffix, downLoadCommon, getFileName } from '@/utils/common';
import { ElMessage, ElMessageBox } from 'element-plus';
import { mediaTypeFilter } from '@/utils/filters';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/index.vue';
import type { UploadInstance } from 'element-plus';

const emit = defineEmits(['onAddPoint', 'onCancelCallBack', 'update:isPointDrawerShow']);
const props = defineProps({
    isPointDrawerShow: {
        type: Boolean,
        default: false,
    },
});
console.log('props', props);
const store = useStore();
const commonList: any = computed(() => store.state.app.common.CommonList);
const activeName = ref('uploadFile');
const activeStep = ref(0);
const uploadLoading = ref(false);
// const uploadTmlRef = ref('');
const uploadFromRef = ref('');
const limitType = reactive({
    types: ['xls', 'xlsx', 'csv'],
});
const tableData = ref([]);
const fileList = ref('');
const uploadFileList = ref<any>([]);
const importForm = reactive({
    mediaType: '',
    fileObsUrl: '',
    fileName: '',
});

const columns = ref([
    {
        label: '导入时间',
        key: 'createTime',
        render: true,
        prop: {
            width: '200px',
        },
    },
    {
        label: '文件名称',
        key: 'fileName',
        render: true,
        prop: {
            width: '220px',
        },
    },
    { label: '媒体类型', key: 'mediaType', render: true },
    { label: '校验结果', key: 'checkStatus', render: true },
]);
const judgeUpload = async (file: any): Promise<void> => {
    let upl: any = null;
    if (window.XCConfig.VUE_APP_ENV === 'prod') {
        // 这里关于环境的判断，各项目跟据自身情况修改
        upl = Upload.createProdUpload();
    } else if (window.XCConfig.VUE_APP_ENV === 'test') {
        upl = Upload.createTestUpload();
    } else if (window.XCConfig.VUE_APP_ENV === 'pre') {
        upl = Upload.createPreUpload();
    } else {
        upl = Upload.createDevUpload();
    }
    const suffix = getSuffix(file.name);

    const types = limitType.types;
    if (!types.includes(suffix)) {
        ElMessage.info('请上传正确的excel格式文件');
        return Promise.reject();
    }
    uploadLoading.value = true;
    upl.upload(file)
        .then((url: any): void => {
            if (url) {
                importForm.fileObsUrl = url;
                importForm.fileName = file.name;
            } else {
                ElMessage.error('上传失败');
            }
            uploadLoading.value = false;
        })
        .catch((e: any) => {
            console.log('e', e);
            uploadLoading.value = false;
            ElMessage.error('上传失败');
        });
};

const httpRequest = async (rawFile: any) => {
    try {
        fileList.value = rawFile.file.name;
        await judgeUpload(rawFile.file);
    } catch (error) {
        console.log(error);
    }
};

const onRemove = async (rawFile: any) => {
    fileList.value = '';
};

const upload = ref<UploadInstance>();

const onCancel = async (formEl: any): Promise<void> => {
    if (!formEl) {
        return;
    }
    activeStep.value = 0;
    formEl.resetFields();
    emit('onCancelCallBack');
};

const openCallBack = async (formEl: any): Promise<void> => {
    if (!formEl) {
        return;
    }
    activeStep.value = 0;
    formEl.resetFields();
};

const importMediaFun = async (): Promise<void> => {
    const params = {
        mediaType: importForm.mediaType,
        fileObsUrl: importForm.fileObsUrl,
        fileName: importForm.fileName,
    };
    try {
        await importMedia(params);
    } catch (error) {
        console.log(error);
    }
};

const downLoadTemp = async (): Promise<void> => {
    let res = '';
    uploadLoading.value = true;
    try {
        res = await downloadTemplate({ mediaType: importForm.mediaType });
        downLoadCommon(res);
        activeStep.value = activeStep.value < 2 ? 2 : activeStep.value;
    } catch (error) {
        console.log(error);
    }
    uploadLoading.value = false;
};

const reloadRecordsFun = async (): Promise<void> => {
    // let res = [];
    uploadLoading.value = true;
    reloadRecords()
        .then((res: any) => {
            tableData.value = res;
        })
        .finally(() => {
            uploadLoading.value = false;
        });
};

const onCheckFile = async (): Promise<void> => {
    activeName.value = 'judgeResult';
    await importMediaFun();
    await reloadRecordsFun();
    ElMessageBox.alert('点击确认导入将录入点位；点击下载查看失败原因', '查看校验结果', {
        confirmButtonText: '确认',
    })
        .then((data) => {
            console.log(data);
        })
        .catch((err) => {
            console.log(err);
        });
};

const changeMediaType = (value: any) => {
    if (value) {
        activeStep.value = activeStep.value < 1 ? 2 : activeStep.value;
    }
};

const handleChange = async (name: any): Promise<void> => {
    if (name === 'judgeResult') {
        reloadRecordsFun();
    }
};

const onRefresh = async (): Promise<void> => {
    await reloadRecordsFun();
};

const onDownloadResult = async (row: any): Promise<void> => {
    if (row.resultUrl) {
        downLoadCommon(row.resultUrl);
    } else {
        ElMessage.error('下载链接为空');
    }
};

const onConfirmImport = async (row: any): Promise<void> => {
    ElMessageBox.confirm('确认后，点位将录入屏盟，同时屏盟会安排工作人员抽检点位', '是否确认导入', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
    })
        .then(async ({ value }) => {
            uploadLoading.value = true;
            try {
                await sureImport(row.fileRecordId);
            } catch (error) {
                console.log(error);
            } finally {
                await reloadRecordsFun();
                // reloadRecordsFun();
            }
            uploadLoading.value = false;
        })
        .catch((err) => {
            console.log(err);
        });
};

const rowConfig = ref([
    {
        color: '#4D88FF',
        name: '刷新',
        type: 'refresh',
        on: (data: any) => {
            onRefresh();
        },
        isPermission: (data: any) => {
            return [1, 2].includes(+data.row.checkStatus);
        },
    },
    {
        color: '#4D88FF',
        name: '下载',
        type: 'download',
        on: (data: any) => {
            onDownloadResult(data.row);
        },
        isPermission: (data: any) => {
            return [3, 5].includes(+data.row.checkStatus);
        },
    },
    {
        color: '#4D88FF',
        name: '确认导入',
        type: 'confirmImport',
        on: (data: any) => {
            onConfirmImport(data.row);
        },
        isPermission: (data: any) => {
            return 3 === +data.row.checkStatus && data.row.successNum && +data.row.successNum !== 0;
        },
    },
]);

// 关闭楼盘图Drawer
const handleClose = () => {
    upload.value!.clearFiles();
    importForm.mediaType = '';
    importForm.fileObsUrl = '';
    importForm.fileName = '';
    activeStep.value = 0;
    uploadFileList.value = [];
};
const beforeClose = () => {
    emit('update:isPointDrawerShow', !props.isPointDrawerShow);
};
const setTableMaxHeightBatch = (): number => {
    let scrollHeight = document.body.scrollHeight;
    let maxHeight = scrollHeight - 270;
    return maxHeight;
};
const maxTableHeight = ref(0);
onMounted(async () => {
    maxTableHeight.value = setTableMaxHeightBatch();
});
</script>

<style lang="scss" scoped>
.batch-import {
    .judge-result {
        .result-tip {
            margin-top: 20px;
            font-size: 14px;
            font-family: PingFang SC-Regular, PingFang SC;
            font-weight: 400;
            color: #bfbfbf;
            line-height: 22px;
            text-align: center;
            margin-bottom: 0;
        }

        .status-button {
            font-size: 14px;
            font-family: PingFang SC-Regular, PingFang SC;
            font-weight: 400;
            color: #ffb414;
            line-height: 22px;
            display: flex;
            flex-direction: column;
        }

        .success-button {
            color: #22ac4e;
        }

        .fail-button {
            color: #e60044;
        }

        .action-right {
            display: flex;
            flex-direction: column;
        }
    }

    .upload-result {
        padding: 20px 0 0 0;
    }

    .upload-file {
        margin-top: 24px;
    }
}

::v-deep {
    .el-form {
        .el-form-item {
            margin-bottom: 64px;
            margin-top: 16px;

            .el-form-item__content {
                margin-left: 0 !important;
            }
        }

        .el-step__title {
            font-size: 16px;
        }

        .el-step__title.is-process {
            color: #333333;
            font-weight: 400;
        }

        .el-upload__text {
            font-size: 14px;
            font-weight: 400;
            color: #333333;
            line-height: 16px;

            .el-upload-span {
                display: block;
                font-size: 12px;
                font-weight: 400;
                color: #808080;
                line-height: 14px;
                margin-top: 10px;
            }
        }

        .is-disable-test {
            color: #cccccc;

            .el-upload-span {
                color: #cccccc;
            }
        }
    }

    .el-tabs {
        .el-tabs__header {
            margin-bottom: 0;
        }
    }
}
</style>
